const { Service } = require('egg');

class GoodsService extends Service {
  // 新增商品
  async addGoods(goodsInfo) {
    try {
      let { name, price, sellNum, goodsImg, content } = goodsInfo;
      await this.app.model.Goods.create({
        goods_name: name,
        goods_price: price,
        goods_sellNum: sellNum,
        goods_img: goodsImg,
        goods_content: content
      });
      return true;
    } catch (error) {
      return false;
    }
  }
  // 获取商品
  // 参数 query 查询项，根据第几页，从第几条获取数据
  async getGoods(query) {
    try {
      let currentPage = parseInt(query.currentPage);
      let pageSize = parseInt(query.pageSize);
      let offset = (currentPage - 1) * pageSize;
      console.log(currentPage, pageSize, offset);
      return await this.app.model.Goods.findAndCountAll({
        order: [
          [ 'createdAt', 'DESC' ]
        ],
        offset,
        limit: pageSize
      });
    } catch (error) {
      return false;
    }
  }
  //  删除商品
  async deleteGoods(id) {
    try {
      await this.app.model.Goods.destroy(
        { where: { id: id } }
      );
      return true;
    } catch (error) {
      return false;
    }
  }
  // 根据id获取一个商品信息
  async getOne(id) {
    try {
      return await this.app.model.Goods.findOne({
        where: {
          id: id
        }
      });
    } catch (error) {
      return false;
    }
  }
  // 修改商品
  async changeGoods(id, newInfo) {
    try {
      let { newName, newPrice, newSellNum, newGoodsImg, newContent } = newInfo;
      await this.app.model.Goods.update({
        goods_name: newName,
        goods_price: newPrice,
        goods_sellNum: newSellNum,
        goods_img: newGoodsImg,
        goods_content: newContent
      }, {
        where: {
          id
        }
      });
      return true;
    } catch (error) {
      return false;
    }
  }
  // 搜索商品
  // 参数 根据商品的名字来搜索
  async searchGoods(query) {
    try {
      let name = query.name;
      let newArr = [];
      let data = await this.app.model.Goods.findAll({
        order: [
          [ 'createdAt', 'DESC' ]
        ]
      });
      data.forEach( item => {
        let dataName = item.dataValues.goods_name;
        // 如果没有就返回，有就存储
        if (dataName.indexOf(name) === -1) {
          return;
        } else {
          newArr.push(item.dataValues);
        }
      });
      return newArr;
    } catch (e) {
      return false;
    }
  }
}

module.exports = GoodsService;
